<template>
  <div class="app-container">
    <el-tabs v-model="activeName" >
      <el-tab-pane label="非空白卡" name="first">
        <div class="filter-container">
          <el-input v-model="listQuery.cardNumber" placeholder="卡号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
          <el-input v-model="listQuery.personCode" placeholder="人员编号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
          <el-select v-model="listQuery.cardStatus" placeholder="卡状态" clearable class="filter-item" style="width: 130px">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            搜索
          </el-button>
          <el-button @click="toggleSelection()">取消多选</el-button>
          <el-button @click="toggleSelection()">统一授权</el-button>
        </div>

        <el-table
          ref="multipleTable"
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @sort-change="sortChange"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          @current-change="toggleRowExpansion"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="卡密码" >
                  <span>{{ props.row.cardPassword }}</span>
                </el-form-item>
                <el-form-item label="卡应用" >
                  <span>{{ props.row.subSystems }}</span>
                </el-form-item>
                <el-form-item label="补贴金额" >
                  <span>{{ props.row.cardSubsidy }}</span>
                </el-form-item>
                <el-form-item label="现金金额" >
                  <span>{{ props.row.cardCash }}</span>
                </el-form-item>
                <el-form-item label="保证金额" >
                  <span>{{ props.row.cardDeposit }}</span>
                </el-form-item>
                <el-form-item label="工本费">
                  <span>{{ props.row.cardCost}}</span>
                </el-form-item>
                <el-form-item label="卡人员所属部门id">
                  <span>{{ props.row.deptId }}</span>
                </el-form-item>

                <el-form-item label="卡人员所属部门名称">
                  <span>{{ props.row.deptName }}</span>
                </el-form-item>
                <el-form-item label="卡片id">
                  <span>{{ props.row.id }}</span>
                </el-form-item>
                <el-form-item label="卡片属性">
                  <span>{{ props.row.isMainCard }}</span>
                </el-form-item>
                <el-form-item label="人员编号">
                  <span>{{ props.row.personCode }}</span>
                </el-form-item>
                <el-form-item label="人员id">
                  <span>{{ props.row.personId }}</span>
                </el-form-item>
                <el-form-item label="人员姓名">
                  <span>{{ props.row.personName }}</span>
                </el-form-item>
                <el-form-item label="使用次数">
                  <span>{{ props.row.availableTimes }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="卡号" prop="id" sortable="custom" align="center"  :class-name="getSortClass('id')">
            <template slot-scope="{row}">
              <span>{{ row.cardNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="开始日期" width="150px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.strStartDate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束日期" width="150px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.strEndDate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="卡类型" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.cardType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="卡类别" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.category }}</span>
            </template>
          </el-table-column>
          <el-table-column label="卡状态" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.cardStatus }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Actions" align="center" width="280" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">
                修改
              </el-button>
              <el-button type="primary" size="mini" >
                换卡
              </el-button>
              <el-button type="primary" size="mini" >
                补卡
              </el-button>
              <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
                退卡
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :append-to-body="true">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
            <el-form-item label="id" prop="id">
              <el-input v-model="temp.id" />
            </el-form-item>
            <el-form-item label="cardNumber" prop="cardNumber">
              <el-input v-model="temp.cardNumber" />
            </el-form-item>
            <el-form-item label="cardPassword" prop="cardPassword">
              <el-input v-model="temp.cardPassword" />
            </el-form-item>
            <el-form-item label="startDate" prop="startDate">
              <el-date-picker v-model="temp.startDate" type="date"  />
            </el-form-item>
            <el-form-item label="endDate" prop="endDate">
              <el-date-picker v-model="temp.endDate" type="date"  />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              Cancel
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              Confirm
            </el-button>
          </div>
        </el-dialog>

<!--        <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">-->
<!--          <el-table :data="pvData" border fit highlight-current-row style="width: 100%">-->
<!--            <el-table-column prop="key" label="Channel" />-->
<!--            <el-table-column prop="pv" label="Pv" />-->
<!--          </el-table>-->
<!--          <span slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>-->
<!--      </span>-->
<!--        </el-dialog>-->
      </el-tab-pane>
      <el-tab-pane label="空白卡" name="second">
        <div class="filter-container">
          <el-input v-model="listQuery1.cardNumber" placeholder="卡号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter1" />
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter1">
            搜索
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
            添加
          </el-button>
        </div>

        <el-table
          :key="tableKey"
          v-loading="listLoading1"
          :data="list1"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @sort-change="sortChange"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          @current-change="toggleRowExpansion"
        ><el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="卡密码" >
                <span>{{ props.row.cardPassword }}</span>
              </el-form-item>
              <el-form-item label="卡应用" >
                <span>{{ props.row.subSystems }}</span>
              </el-form-item>
              <el-form-item label="补贴金额" >
                <span>{{ props.row.cardSubsidy }}</span>
              </el-form-item>
              <el-form-item label="现金金额" >
                <span>{{ props.row.cardCash }}</span>
              </el-form-item>
              <el-form-item label="保证金额" >
                <span>{{ props.row.cardDeposit }}</span>
              </el-form-item>
              <el-form-item label="工本费">
                <span>{{ props.row.cardCost}}</span>
              </el-form-item>
              <el-form-item label="卡人员所属部门id">
                <span>{{ props.row.deptId }}</span>
              </el-form-item>

              <el-form-item label="卡人员所属部门名称">
                <span>{{ props.row.deptName }}</span>
              </el-form-item>
              <el-form-item label="卡片id">
                <span>{{ props.row.id }}</span>
              </el-form-item>
              <el-form-item label="卡片属性">
                <span>{{ props.row.isMainCard }}</span>
              </el-form-item>
              <el-form-item label="人员编号">
                <span>{{ props.row.personCode }}</span>
              </el-form-item>
              <el-form-item label="人员id">
                <span>{{ props.row.personId }}</span>
              </el-form-item>
              <el-form-item label="人员姓名">
                <span>{{ props.row.personName }}</span>
              </el-form-item>
              <el-form-item label="使用次数">
                <span>{{ props.row.availableTimes }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
          <el-table-column label="卡号" prop="id" sortable="custom" align="center"  :class-name="getSortClass('id')">
            <template slot-scope="{row}">
              <span>{{ row.cardNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="开始日期" width="150px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.strStartDate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束日期" width="150px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.strEndDate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="卡类型" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.cardType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="卡类别" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.category }}</span>
            </template>
          </el-table-column>
          <el-table-column label="卡状态" width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.cardStatus }}</span>
            </template>
          </el-table-column>

          <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">
                人员开卡
              </el-button>
              <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
                删除卡片
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
            <el-form-item label="Type" prop="type">
              <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
                <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item label="Date" prop="timestamp">
              <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date" />
            </el-form-item>
            <el-form-item label="Title" prop="title">
              <el-input v-model="temp.title" />
            </el-form-item>
            <el-form-item label="Status">
              <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
                <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="Imp">
              <el-rate v-model="temp.importance" :colors="['#99A9BF', '#F7BA2A', '#FF9900']" :max="3" style="margin-top:8px;" />
            </el-form-item>
            <el-form-item label="Remark">
              <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              Cancel
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              Confirm
            </el-button>
          </div>
        </el-dialog>

        <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
          <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
            <el-table-column prop="key" label="Channel" />
            <el-table-column prop="pv" label="Pv" />
          </el-table>
          <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>

  </div>

</template>

<script>
  import { getList } from '@/api/card'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  const calendarTypeOptions = [
    { key: '激活', display_name: '激活' },
    { key: '冻结', display_name: '冻结' },
    { key: '注销', display_name: '注销' }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        getRowKeys(row) {
          return row.id;
        },
        form: {},
        expands: [],
        multipleSelection: [],
        tableKey: 0,
        list: null,
        list1: null,
        total: 0,
        total1: 0,
        listLoading: true,
        listLoading1: true,
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          cardNumber: undefined,
          cardStatus: undefined,
          personCode: undefined,
        },
        listQuery1: {
          pageNum: 1,
          pageSize: 20,
          cardNumber: undefined,
          cardStatus: '空白',
        },
        activeName:'first',
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          cardNumber: undefined,
          cardPassword: '',
          startDate: undefined,
          endDate: undefined,
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
      this.getList1()
    },
    methods: {
      getList() {
        this.listQuery.cardStatus = '激活'
        this.listLoading = true
        getList(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },

      getList1() {
        this.listLoading1 = true
        getList(this.listQuery1).then(response => {
          this.list1 = response.data.items
          this.total1 = response.data.total

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading1 = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },

      handleFilter1() {
        this.listQuery1.page = 1
        this.getList1()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      toggleRowExpansion(row){
        this.expands = [];
        this.expands.push(row.id);
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      }
    }
  }
</script>

<style type="text/css">

  /* 展开的form样式 */
  .demo-table-expand label {
    width: 140px;
    color: #99a9bf;
  }

  .el-form--label-left .el-form-item__label {
    text-align: right;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 30%;
  }

  .container_table .fy {
    margin-top: 20px;
  }
</style>
